package com.jh.user.business.impl;

import cn.jh.common.pojo.BaseResponse;
import cn.jh.common.utils.BeanUtil;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import com.jh.user.business.TerminalInfoBussiness;
import com.jh.user.pojo.ShopRegister;
import com.jh.user.pojo.StoreInfo;
import com.jh.user.pojo.TerminalInfo;
import com.jh.user.repository.ShopRegisterRepository;
import com.jh.user.repository.TerminalInfoRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
public class TerminalInfoBussinessImpl implements TerminalInfoBussiness {
    @Autowired
    private TerminalInfoRepository terminalInfoRepository;
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private ShopRegisterRepository shopRegisterRepository;

    private Specification<TerminalInfo> where(final String shopId, final String shopName, final Integer terminalType, final String terminalNo, final String machineNo, final String evmNo, final String startTime, final String endTime) {
        return new Specification<TerminalInfo>() {
            @Override
            public Predicate toPredicate(Root<TerminalInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(shopId)) {
                    predicates.add(criteriaBuilder.equal(root.<String>get("shopId"), shopId));
                }
                if (StringUtils.isNotBlank(shopName)) {
                    predicates.add(criteriaBuilder.equal(root.<String>get("shopName"), shopName));
                }
                if (terminalType != null) {
                    predicates.add(criteriaBuilder.equal(root.<Integer>get("terminalType"), terminalType));
                }
                if (StringUtils.isNotBlank(terminalNo)) {
                    predicates.add(criteriaBuilder.equal(root.<String>get("terminalNo"), terminalNo));
                }
                if (StringUtils.isNotBlank(machineNo)) {
                    predicates.add(criteriaBuilder.equal(root.<String>get("machineNo"), machineNo));
                }
                if (StringUtils.isNotBlank(evmNo)) {
                    predicates.add(criteriaBuilder.equal(root.<String>get("evmNo"), evmNo));
                }
                if (StringUtils.isNotBlank(startTime)) {
                    predicates.add(criteriaBuilder.greaterThan(root.<Date>get("createTime"), DateUtil.getYYMMHHMMSSDateFromStr(startTime)));
                }
                if (StringUtils.isNotBlank(endTime)) {
                    predicates.add(criteriaBuilder.lessThan(root.<Date>get("createTime"), DateUtil.getYYMMHHMMSSDateFromStr(endTime)));
                }

                return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }


    @Override
    public Page<TerminalInfo> findByShopIdAndShopNameAndTerminalTypeAndTerminalNo(String shopId, String shopName, Integer terminalType, String terminalNo, String machineNo, String evmNo, String startTime, String endTime, Pageable pageable) {
        return terminalInfoRepository.findAll(where(shopId, shopName, terminalType, terminalNo, machineNo, evmNo, startTime, endTime), pageable);
    }

    @Transactional
    @Override
    public Object mergeTerminalInfo(TerminalInfo terminalInfo) {

        ShopRegister shopName = shopRegisterRepository.findByShopId(terminalInfo.getShopId());
        if (shopName == null) {
            return BaseResponse.error(CommonConstants.FALIED, "商户号不存在");
        }
        terminalInfo.setShopName(shopName.getShopName());
        terminalInfo.setTerminalNo(System.currentTimeMillis() + "" + new Random().nextInt(5));
        terminalInfo.setStoreName("".equals(terminalInfo.getStoreName()) ? null : terminalInfo.getStoreName());
        terminalInfo.setStoreNo("".equals(terminalInfo.getStoreNo()) ? null : terminalInfo.getStoreNo());
        terminalInfo.setMachineNo("".equals(terminalInfo.getMachineNo()) ? null : terminalInfo.getMachineNo());
        terminalInfo.setMachineType(terminalInfo.getMachineType());
        terminalInfo.setSimNo("".equals(terminalInfo.getSimNo()) ? null : terminalInfo.getSimNo());
        terminalInfo.setTerminalName("".equals(terminalInfo.getTerminalName()) ? null : terminalInfo.getTerminalName());
        terminalInfo.setShopLogo("".equals(terminalInfo.getShopLogo()) ? null : terminalInfo.getShopLogo());
        terminalInfo.setEvmImg("".equals(terminalInfo.getEvmImg()) ? null : terminalInfo.getEvmImg());
        terminalInfo.setPayUrl("".equals(terminalInfo.getPayUrl()) ? null : terminalInfo.getPayUrl());
        terminalInfo.setEvmNo("".equals(terminalInfo.getEvmNo()) ? System.currentTimeMillis() + "" + new Random().nextInt(5) :terminalInfo.getEvmNo());
        terminalInfo.setCreateTime(new Date());
        TerminalInfo save = terminalInfoRepository.save(terminalInfo);
        entityManager.flush();
        return save;
    }

    @Override
    @Transactional
    public void updateTerminalPos(TerminalInfo terminalInfo) throws Exception {
        HashMap<Object, Object> map = new HashMap<>();
        ShopRegister shopName = shopRegisterRepository.findByShopId(terminalInfo.getShopId());
        if (shopName == null) {
            throw new Exception("商户号不存在");
        }
        TerminalInfo info = terminalInfoRepository.findByMachineNoAndTerminalNo(terminalInfo.getMachineNo(), terminalInfo.getTerminalNo());
        terminalInfo.setSimNo(null);
        terminalInfo.setMachineType(null);
        terminalInfo.setMachineNo(null);
        terminalInfo.setId(null);
        terminalInfo.setUserId(null);
        BeanUtil.copyPropertiesIgnoreNull(terminalInfo, info);
        entityManager.merge(info);
        entityManager.flush();


    }

    @Override
    @Transactional
    public void updateTerminalTk(TerminalInfo terminalInfo) throws Exception {
        HashMap<Object, Object> map = new HashMap<>();
        ShopRegister shopName = shopRegisterRepository.findByShopId(terminalInfo.getShopId());
        if (shopName == null) {
            throw new Exception("商户号不存在");
        }
        TerminalInfo info = terminalInfoRepository.findByEvmNoAndTerminalNo(terminalInfo.getEvmNo(), terminalInfo.getTerminalNo());
        terminalInfo.setId(null);
        terminalInfo.setUserId(null);
        BeanUtil.copyPropertiesIgnoreNull(terminalInfo, info);
        entityManager.merge(info);
        entityManager.flush();
    }

    @Override
    @Transactional
    public void deleteTerminalInfo(String shopId,String terminalInfo) throws Exception {
        HashMap<Object, Object> map = new HashMap<>();
        ShopRegister shopName = shopRegisterRepository.findByShopId(shopId);
        if (shopName == null || "".equals(shopName.getShopName())) {
            throw new Exception("商户号查询为空");
        }
        terminalInfoRepository.deleteByShopIdAndTerminalNo(shopId, terminalInfo);
    }

    @Override
    public Object findByShopId(String shopId) {
        HashMap<Object, Object> map = new HashMap<>();
        ShopRegister shopName = shopRegisterRepository.findByShopId(shopId);
        if (shopName == null) {
            return BaseResponse.error("商户号不存在");
        }

        return terminalInfoRepository.findByShopId(shopId);
    }


}

